// pages/mystore/address/index.js
import {apiUrls, makeRequest } from '../../../utils/api';
const App = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    id:0,
    lng: '',
    lat: '',
    address: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    that.setData({
      id: options.id
    })
    that.wxValidate = App.wxValidate(
      {
        address: {
          required: true,
          minlength: 2,
          maxlength: 100,
        },
        lng: {
          required: true,
        },
        lat: {
          required: true,
        }
      }
      , {
        address: {
          required: '请选择地址',
        },
        lng: {
          required: '位置必须选择'
        },
        lat: {
          required: '位置必须选择'
        }
      }
    );
    makeRequest({
      url: apiUrls.getShopDetail(options.id),
      method: 'GET',
      data: {
        include: 'category,manager,area'
      },
      success: function (res) {
        that.setData({
          address: res.data.data.address,
          lng: res.data.data.lng,
          lat: res.data.data.lat,
        })
      }
    });
  },
  bindSubmit(e) {
    let that = this;
    //提交错误描述
    if (!this.wxValidate.checkForm(e)) {
      const error = this.wxValidate.errorList[0]
      // `${error.param} : ${error.msg} `
      wx.showToast({
        title: `${error.msg} `,
        image: '/images/errors.png',
        duration: 500
      })
      return false
    }
    else {
      makeRequest({
        url: apiUrls.putAddressEdit(that.data.id),
        method: 'PUT',
        data: e.detail.value,
        success: function (res) {
          console.log(res);
          if (res.statusCode === 422) {
            wx.showToast({
              title: `${res.data.data[Object.keys(res.data.data)[0]][0]} `,
              image: '/images/errors.png',
              duration: 2000
            })
          } else if (res.statusCode === 200) {
            wx.showToast({
              title: '保存成功',
              duration: 2000,
              success: function () {
                setTimeout(function(){
                  wx.navigateBack({
                    delta: 1
                  });
                }, 1000);
              }
            });
          }
        }
      });
    }
    //console.log(e.detail.value)
  },
  openChooseLocationMap: function () {
    const that = this;
    wx.chooseLocation({
      success: function (res) {
        that.setData({         
          address: res.address + '(' + res.name + ')',
          lng: res.longitude,
          lat: res.latitude
        });
      },
    })
  }
})